import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)

const state = {
  favorites: [],
  username: "",
  token:"",
  userInfo: {}, // 登录后的用户信息
}

const mutations = {
  setUsername: (state, value) => {
    state.username = value;
  },
  setUserInfo: (state, userInfo) => {
	// console.log('===========',userInfo)
    state.userInfo = userInfo
    state.username = userInfo.username
	state.token = userInfo.token
	console.log('===========',state.token)
  },
  clearUserInfo: (state) => {
    state.userInfo = {}
    state.username = ""
  }
}

const getters = {
  // 判断是否登录
  isLoggedIn: (state) => !!state.userInfo && !!state.userInfo.token
}

// 模块自动加载
let modules = {}
const files = require.context('./modules', false, /\.js$/)
files.keys().forEach((key) => {
  modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

export default new Vuex.Store({
  modules,
  state,
  mutations,
  getters,
  plugins: [
    createPersistedState({
      key: 'app_config_data',
      paths: ['favorites', 'username', 'userInfo','token'],
      storage: {
        getItem: (key) => uni.getStorageSync(key),
        setItem: (key, value) => uni.setStorageSync(key, value),
        removeItem: (key) => uni.removeStorageSync(key),
      }
    })
  ]
})
